import { useMenuStore } from '@/store/menuStore';
import { RouteRecordRaw } from 'vue-router';
import { loadVueFile } from './index';

/**
 * 将数据转成路由树结构
 * @param menus 菜单数据
 * @param pid 父级id
 * @returns
 */
export const listToRoutes = (menus: ISystem.IMenu[], pid: string): RouteRecordRaw[] => {
	if (menus.length <= 0) {
		return [];
	}
	const routes: RouteRecordRaw[] = [];
	menus.map((menu: ISystem.IMenu) => {
		if (pid === menu.pid) {
			const children = listToRoutes(menus, menu.id);
			const componentPath = `../views${menu.component}.vue`;
			const layoutPath = `..${menu.component}.vue`;
			// 有子菜单就用layout，没有就直接用component
			const component = children.length ? loadVueFile(layoutPath) : loadVueFile(componentPath);
			const route: RouteRecordRaw = {
				path: menu.path,
				redirect: children.length ? children[0].path : undefined,
				component,
				children,
				meta: {
					menu,
				},
			};
			routes.push(route);
		}
	});
	return routes;
};

/**
 * 将数据转成菜单树结构
 * @param menus 菜单数据
 * @param pid 父级id
 * @returns
 */
export const listToTree = (menus: ISystem.IMenu[], pid: string) => {
	if (menus.length <= 0) {
		return [];
	}
	const list: ISystem.IMenu[] = [];
	menus.map((menu: ISystem.IMenu) => {
		if (pid === menu.pid) {
			list.push({
				...menu,
				children: listToTree(menus, menu.id),
			});
		}
	});
	return list;
};

/**
 * 通过id/key获取menus中匹配的数据
 * @param value id/key
 * @returns
 */
export const getMenuByAttr = (value: string, attr: keyof ISystem.IMenu) => {
	const menuStore = useMenuStore();
	return menuStore.menus.find((menu) => menu[attr] === value);
};
